﻿using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Avalonia.Controls;
using DevManager.Models;

namespace DevManager.Pages;

public partial class DownloadPage : PageBase
{
    public DownloadPage(Language language)
    {
        InitializeComponent();
        NameBlock = this.FindControl<TextBlock>("NameBlock")!;
        DownlandBox = this.FindControl<ComboBox>("DownlandBox")!;
        NameBlock.Text = language.Name;
        DownlandBox.ItemsSource = language.LanguageItems;
        DownlandBox.SelectedIndex = 0;
    }

    public (string url, string path) GetResult()
    {
        if (DownlandBox.SelectedItem is not LanguageItem item) return ("", "");
        var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        var url = "";
        if (OperatingSystem.IsWindows())
        {
            var d = item.DownloadUrls.FirstOrDefault(x => x.Name == "Windows");
            if (d == null) return ("", "");
            url = d.Url;
            path = Path.Combine(path, $"{item.Name}.{d.Extension}");
        }
        else if (OperatingSystem.IsMacOS())
        {
            var architecture = RuntimeInformation.ProcessArchitecture is Architecture.X64 or Architecture.X86
                ? "arm"
                : "x86";
            var d = item.DownloadUrls.FirstOrDefault(x => x.Name == $"Mac({architecture})");
            if (d == null) return ("", "");
            url = d.Url;
            path = Path.Combine(path, $"{item.Name}.{d.Extension}");
        }
        else if (OperatingSystem.IsLinux())
        {
            // var os = Environment.OSVersion;
            var d =item.DownloadUrls.FirstOrDefault(x => x.Name == "Linux");
            if (d == null) return ("", "");
            url = "Order";
            path = d.Url;
        }

        return (url, path);
    }
}